<template>
    <div @click="cancelSelect" class="container">
       
        <div @click.stop="1==1" class="canvas-p">
            <canvas  :id="id" :width="width" :height="height"></canvas>
        </div>
        
    </div>
    
   
</template>
<script>
import { fabric } from 'fabric'
import bus from '../bus/bus'
export default {
    props: {
        width: Number,
        height: Number
    },
    watch: {
        width: function(){
            fabricCanvas.canvas.setWidth(this.width)
        },
        height: function(){
            fabricCanvas.canvas.setHeight(this.height)
        }
    },
    data(){
        return {
            id: Math.random() + '',
            canvas: null,
        }
    },
    methods: {
        init(){
            this.canvas =new fabric.Canvas(this.id)

            window.fabricCanvas = this

            this.canvas.preserveObjectStacking = true

            var deleteIcon = document.createElement('img');
            deleteIcon.src = require('../img/close.png')

            fabric.Object.prototype.transparentCorners = false;
            fabric.Object.prototype.cornerColor = 'blue';
            fabric.Object.prototype.cornerStyle = 'circle';
        
            fabric.Object.prototype.controls.deleteControl = new fabric.Control({
                x: 0.5,
                y: -0.5,
                offsetY: 16,
                cursorStyle: 'pointer',
                mouseUpHandler: function(eventData, transform){
                var target = transform.target;
                var canvas = target.canvas;
                    

                   

                    var list = canvas.getActiveObjects()
                   
                    for(var item of list){
                        canvas.remove(item);
                    }
                    canvas.discardActiveObject()
                     canvas.requestRenderAll(); 
                    
                    
                },
                render: function(ctx, left, top, styleOverride, fabricObject) {
                
                    var size = this.cornerSize;
                    ctx.save();
                    ctx.translate(left, top);
                    ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle));
                
                    ctx.drawImage(deleteIcon, -size/2, -size/2, size, size);
                    ctx.restore();
                },
                cornerSize: 24
            })
        },

        bindEvent(){
           
            this.canvas.on({
                'object:moving': (e) => {
                    bus.$emit('object:modified',  e.target)
                },  
                'object:scaling': (e) => {
                    bus.$emit('object:modified',  e.target)
                },
                'object:rotating': (e) => {
                    bus.$emit('object:modified',  e.target)
                },
                'object:modified': (e) => {
                   
                    bus.$emit('object:modified',  e.target)
                },
                'selection:cleared': (e) => {
                  
                    bus.$emit('selection:cleared')
                },
                'selection:created': (e) => {
                   
                    bus.$emit('selection:created', e.selected)
                },
                'selection:updated': (e) => {
                 
                    bus.$emit('selection:updated', e.selected)
                },
            });
            
        },
    
        addRect({width, height, left, top, fill}){
        
            var rect = new fabric.Rect({
                left: left,//距离画布左侧的距离，单位是像素
                top:top,//距离画布上边的距离
                fill:fill,//填充的颜色
                width:width,//方形的宽度
                height:height//方形的高度
        
            })
            this.canvas.add(rect)
        },
        
        addImg({url}){
        
            fabric.Image.fromURL(url, (oImg) => {
                
                this.canvas.add(oImg);
            });
        },

        addBackground({url}){
            fabric.Image.fromURL(url, (oImg) => {
                
                this.canvas.add(oImg);

                this.canvas.sendToBack(oImg)
            });
        },
        addText({text}){
            var str = new fabric.Text(text, {
                fontSize: 20,
                fill: '#000',
                left: 40,
                top:40,
             
            })
            this.canvas.add(str);
        },
        addHead(){
            // if(this.haveObject('studentHead')){
            //     this.$message.error('已经添加了头像')
            //     return
            // }

            var url = 'https://cdn.xueerqin.net/school/user.png?a=1'
            fabric.Image.fromURL(url, (oImg) => {
                    oImg.tag = 'studentHead'
                    oImg.top = 70
                    

                  
                this.canvas.add(oImg);

                let cw = this.canvas.getWidth()
                let w = oImg.width
                oImg.set('left', (cw - w) / 2).setCoords()

            });
        },
        addSchoolName(){
            // if(this.haveObject('schoolName')){
            //     this.$message.error('已经添加了学校名称')
            //     return
            // }

            var schoolName = this.$store.state.common.cookiesObj.classList[0].SchoolName
           
            var label = new fabric.Text(schoolName, {
                fontSize: 13,
                fill: '#000',
               
                top: 10,
                tag: 'schoolName'
            })
            this.canvas.add(label)
            let cw = this.canvas.getWidth()
            let lw = label.width
            label.set('left', (cw -lw) / 2).setCoords()
        },
        addName(){
            // if(this.haveObject('studentName')){
            //     this.$message.error('已经添加了学生姓名')
            //     return
            // }

            var label = new fabric.Text('姓名  ', {
                fontSize: 12,
                fill: '#000',
                left: 12,
                top: 210,
            })
            var name = new fabric.Text('小明', {
                fontSize: 12,
                fill: '#000',
                left: 40,
                top: 210,
                tag: 'studentName'
            })
            this.canvas.add(name);
            this.canvas.add(label)
            let cw = this.canvas.getWidth()
            let nw = name.width * 2
            let lw = label.width
          
            name.set('left', label.left + lw).setCoords()

            this.addRect({
                width: 60,
                height: 1,
                left: label.left + lw,
                top: 226,
                fill: '#000'
            })
        },
        addClass(){
            // if(this.haveObject('className')){
            //     this.$message.error('已经添加了班级名称')
            //     return
            // }

             var label = new fabric.Text('班级  ', {
                fontSize: 12,
                fill: '#000',
                left: 12,
                top: 240,
            })

            var clas = new fabric.Text('班级名称', {
                fontSize: 12,
                fill: '#000',
                left: 40,
                 top: 240,
              
                tag: 'className'
            })
           

            this.canvas.add(clas);
            this.canvas.add(label)
            let w = this.canvas.getWidth()
            let cw = clas.width
          
            let lw = label.width
           
            

            clas.set('left', label.left + lw).setCoords()

            this.addRect({
                width: 60,
                height: 1,
                left: label.left + lw,
                top: 256,
                fill: '#000'
            })
        },
        addNum(){
            // if(this.haveObject('num')){
            //     this.$message.error('已经添加了座号')
            //     return
            // }

             var label = new fabric.Text('座号  ', {
                fontSize: 12,
                fill: '#000',
                left: 12,
                top: 270,
            })

            var num = new fabric.Text('101', {
                fontSize: 12,
                 fill: '#000',
                left: 40,
                top: 270,
              
                tag: 'num'
            })
           

            this.canvas.add(num);
            this.canvas.add(label)
            let w = this.canvas.getWidth()
          
            let lw = label.width
           
          

            num.set('left', label.left + lw).setCoords()

            this.addRect({
                width: 60,
                height: 1,
                left: label.left + lw,
                top: 286,
                fill: '#000'
            })
        },

        addCode(){
            // if(this.haveObject('code')){
            //     this.$message.error('已经添加了学生二维码')
            //     return
            // }

             fabric.Image.fromURL('https://cdn-1258963190.cos.ap-guangzhou.myqcloud.com/school/code.png?a=2', (oImg) => {
                oImg.top = 222
                oImg.left = 114
                oImg.tag = 'code'
                this.canvas.add(oImg);
            });

        
        },

        toJSON(){
            return this.canvas.toJSON(['tag'])
        },
        loadFromJSON(json){
            this.canvas.loadFromJSON(json)
        },
        cancelSelect(){
             this.canvas.discardActiveObject().renderAll()
        },

        haveObject(tag){
            var list = this.canvas.getObjects()
            var flag = false
            for(var item of list){
                if(item.tag == tag){
                    flag = true
                }
            }

            return flag

        }

  },
  mounted(){
    this.init()
    this.bindEvent()

    
  }
}
</script>
<style scoped>
.container{
    width: 600px; text-align: center;
    padding: 30px 0; margin: 0 20px;
}
.canvas-p{
    margin: 0 auto; display: inline-block;
    border: 1px solid #ccc
}

</style>